﻿/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
**     the names of its contributors may be used to endorse or promote
**     products derived from this software without specific prior written
**     permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QDateTime>
#include <QMainWindow>
#include <QStatusBar>
#include <QMessageBox>
#include <QMenuBar>
#include <QApplication>
#include <QPainter>
//#include <QPrinter>
//#include <QPrintDialog>
#include <QLabel>
#include <QImage>
#include <QProgressDialog>
#include <QPixmap>
#include <QMouseEvent>
#include <QStyleOptionGraphicsItem>
#include <QDebug>
#include <QAbstractSlider>
#include <QUndoStack>

#include "canvas.h"
#include "MoveCell.h"
#include "JistDocumentHandler.h"
void JistSimpleTextItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
  painter->fillRect(option->rect, QColor(255,255,255,180));
   QGraphicsSimpleTextItem::paint(painter, option, widget );
}


FigureEditor::FigureEditor(QVector< QVector< QList< JistCommonData > > > *cellData, QWidget* parent, const char* name, Qt::WindowFlags f)
    :m_ScaleX(1.0f), m_ScaleY(1.0f)
    ,m_bShowGrid(false)
    ,m_iAnimationIndex(0)
    ,m_iFrameIndex(0)
    ,m_bLoopAni(true)
    ,m_bAniPlaying(false)
    ,m_bReverse(false)
    ,m_CellData(*cellData)
    ,m_bMovable(true)
    ,m_IsAdditive(false)
    ,m_selectEditingItem(NULL)
    ,m_bDragMovable(true)
    ,m_bShowEnermy(false)
    ,m_bGroupBand(false)
    ,m_TextItem(NULL)
    ,m_pDocument(NULL)
    ,m_eViewMode(DEFAULT_VIEW)
    ,m_AnchorVLine(NULL)
    ,m_AnchorHLine(NULL)
    ,m_bEmptySprite(false)
{
    m_canvas.setBackgroundBrush(QColor(80,80,80));
    QGraphicsView(&m_canvas, parent);
    setAcceptDrops(true);
    setObjectName(tr(name));
    setWindowFlags(f);
    // 픽셀 보정
    //setRenderHints(QPainter::Antialiasing | QPainter::HighQualityAntialiasing);
    clear();
    this->setScene(&m_canvas);
    m_pModel = NULL;
    QGraphicsView::setAlignment(Qt::AlignCenter);
    setAlignment(Qt::AlignCenter);
    setResizeAnchor(QGraphicsView::AnchorViewCenter);
}

void FigureEditor::setViewMode(ViewMode mode)
{
    m_eViewMode = mode;
}

void FigureEditor::clear()
{
    if(scene()){
        scene()->clear();
    }
    m_canvas.clear();
    update();
    this->centerOn(0,0);
    m_EnermyImage = QImage();
    setRect(QRect(0,0,960,640));
    m_RectItem = NULL;
    m_TextItem = NULL;

}

void FigureEditor::keyPressEvent ( QKeyEvent * event )
{
    m_Selectlist = m_canvas.selectedItems();
    ImageItem *item = NULL;
    int delta = 1;
    if (event->modifiers() == Qt::ShiftModifier)
    {
          delta = 10;
    }
    // 포커스를 셀 테이블 위젯으로 이동
    if(m_pDocument && !m_IsAdditive && event->key() == Qt::Key_Alt){// && !event->isAutoRepeat())
        QApplication::setActiveWindow (m_pDocument->m_CellTableWidget );
        m_pDocument->m_CellTableWidget->setFocus();
        return;
    }
    // 영역선택 모드
    if (m_IsAdditive && event->modifiers() == Qt::ShiftModifier)
    {
          m_bGroupBand = !m_bGroupBand;
          setDragMode(m_bGroupBand ? QGraphicsView::NoDrag : QGraphicsView::ScrollHandDrag);
    }

    if(event->modifiers() == Qt::AltModifier)
    {
        m_bEmptySprite = true;
    }

    if(m_Selectlist.count()){
        m_selectEditingItem = item = (ImageItem*)m_Selectlist[0];
        m_selectedStartPos = m_selectEditingItem->pos().toPoint();
        m_startPos = m_selectedStartPos;
    }
    if (item && event->key() == Qt::Key_Left)
    {
        for(int k = 0; k < m_Selectlist.count(); k++){
            ImageItem* item = (ImageItem*)m_Selectlist[k];
            item->setPos(item->x() - delta, item->y());
        }
    }
    else if (item && event->key() == Qt::Key_Right)
    {
        for(int k = 0; k < m_Selectlist.count(); k++){
            ImageItem* item = (ImageItem*)m_Selectlist[k];
            item->setPos(item->x() + delta, item->y());
        }
    }
    else if (item && event->key() == Qt::Key_Up)
    {
        for(int k = 0; k < m_Selectlist.count(); k++){
            ImageItem* item = (ImageItem*)m_Selectlist[k];
            item->setPos(item->x(), item->y() - delta);
        }
    }
    else if (item && event->key() == Qt::Key_Down)
    {
        for(int k = 0; k < m_Selectlist.count(); k++){
            ImageItem* item = (ImageItem*)m_Selectlist[k];
            item->setPos(item->x(), item->y() + delta);
        }
    }
}

void FigureEditor::keyReleaseEvent( QKeyEvent * event )
{
    // 좌표 표시
    if(m_selectEditingItem )
        emit changeSelItemPos(m_selectEditingItem->pos().toPoint(), m_selectEditingItem->getId(), m_selectEditingItem->rect().toRect());
    // 언두 키보드 입력 무시
    if(m_selectEditingItem && (event->key() == Qt::Key_Left || event->key() == Qt::Key_Right || event->key() == Qt::Key_Up || event->key() == Qt::Key_Down))
        finishMoving(m_selectEditingItem->pos());

    if(event->modifiers() == Qt::AltModifier)
    {
        m_bEmptySprite = false;
    }
//    if (m_IsAdditive && event->key() == Qt::Key_Shift)
//    {
//          m_bGroupBand = false;
//          setDragMode(QGraphicsView::NoDrag);
//    }
}

void FigureEditor::mousePressEvent(QMouseEvent *event)
{
    //if(event->button() == Qt::RightButton)
    //    this->parent()->on_pushButton_clicked();
    if(m_bMovable || m_bDragMovable)
        QGraphicsView::mousePressEvent(event);

    QSize tempSize = m_Img.size();
    // 창크기 변경시 클릭좌표 보정 취소 => 이미지 교체시 중앙정렬 미완성
    QPoint mp = QPoint(0,0);//QPoint((rect.width() - tempSize.width()*m_ScaleX)/2, (rect.height() - tempSize.height()*m_ScaleY)/2);

    QScrollBar *hb = horizontalScrollBar();
    int hValue = ((QAbstractSlider*)hb)->value();

    QScrollBar *vb = this->verticalScrollBar();
    int vValue = ((QAbstractSlider*)vb)->value();
    int w = m_canvas.width();
    int h = m_canvas.height();

    QRect fRect = this->rect();
    QPoint thisPos = this->pos();
    int scrW = 0;
    int scrH = 0;
    int x = (event->pos().x() - mp.x() + hValue) / m_ScaleX;
    int y = (event->pos().y() - mp.y() + vValue) / m_ScaleY;
//    if(fRect.height() < h * m_ScaleX)
//    {
//        scrW = 10;
//        x = (event->pos().x() - (fRect.width() - w * m_ScaleX)/2)  + scrW;
//    }
//    if(fRect.width() < w * m_ScaleY){
//        scrH = 10;
//        y = (event->pos().y() - (fRect.height() - h * m_ScaleY)/2) + scrH;
//    }
//    QPoint p2((event->pos().x() - (fRect.width() - vb->width() - w * m_ScaleX)/2)  + scrW, (event->pos().y() - (fRect.height() - hb->height() - h * m_ScaleY)/2) + scrH);
//    QPoint baseImgPos =  m_enermyPix->pos().toPoint();
    QPoint asolutePos(x, y);
    QRgb c =  m_Img.pixel(asolutePos);
    QList<QGraphicsItem *> list = m_canvas.selectedItems();
    m_Selectlist = list;
    if(list.count())
        m_selectEditingItem = (ImageItem*)list[0];
    else{
        m_selectEditingItem = NULL;
        if(m_bMovable)
            m_pDocument->m_CellTableWidget->clearSelection();
    }
    //m_selectEditingItem = (ImageItem*)m_canvas.itemAt(p);

    m_startPos = m_canvas.GetTouchPos();
    if(m_selectEditingItem){
        m_selectedStartPos = m_selectEditingItem->pos().toPoint();
        setDragMode(QGraphicsView::NoDrag);
    }
    else if(!m_bGroupBand){
        setDragMode(QGraphicsView::ScrollHandDrag);
    }
    if(m_IsAdditive)
    {
        if(!m_bGroupBand)
        {
            QRect r = computeFillRegion(m_startPos.toPoint() - m_enermyPix->pos().toPoint());
            r.translate(GetAnchorPos());
            if(m_SelectRect == r)
                return;
            m_SelectRect = r;
            r.translate(m_enermyPix->pos().toPoint() - GetAnchorPos());
            if(m_RectItem)
                scene()->removeItem(m_RectItem);
            m_RectItem = scene()->addRect(r);
            //m_RectItem->setFlag(QGraphicsItem::ItemIsMovable);
            //int z = qrand()%256;
            m_RectItem->setBrush( QColor(50,50,50) );
            m_RectItem->setPen( QPen(QColor(50,50,50), 0) );
            m_RectItem->setZValue(100);
            m_RectItem->setOpacity(0.5f);

            if(m_TextItem){
                scene()->removeItem(m_TextItem);
            }
            //m_TextItem = (JistSimpleTextItem*)scene()->addSimpleText(QString(QLatin1String("[x:%1, y:%2, w:%3, h:%4]")).arg(r.x()).arg(r.y()).arg(r.width()).arg(r.height()));
            m_TextItem = new JistSimpleTextItem;
            m_TextItem->setText(QString(QLatin1String("[x:%1, y:%2, w:%3, h:%4]")).arg(m_SelectRect.x()).arg(m_SelectRect.y()).arg(m_SelectRect.width()).arg(m_SelectRect.height()));
            m_TextItem->setScale(1/m_ScaleX);
            m_TextItem->setPos(QPoint(r.bottomRight()));
            scene()->addItem(m_TextItem);
        }
    }
    //m_canvas.clearSelection();
}


void FigureEditor::mouseMoveEvent(QMouseEvent *event)
{
    QPoint mp = QPoint(0,0);
    QScrollBar *hb = horizontalScrollBar();
    int hValue = ((QAbstractSlider*)hb)->value();

    QScrollBar *vb = this->verticalScrollBar();
    int vValue = ((QAbstractSlider*)vb)->value();

    QPoint glovalPos = event->globalPos();
    int ex = event->pos().x();
    if(ex < 0)
        ex = 0;
    int ey = event->pos().y();
    if(ey < 0)
        ey = 0;
    QRect fRect = this->rect();
    int scrW = 0;
    int scrH = 0;
    int w = m_canvas.width();
    int h = m_canvas.height();
    QPoint p2 = m_canvas.GetTouchPos();//((event->pos().x() - (fRect.width() - w * m_ScaleX)/2)  + scrW, (event->pos().y() - (fRect.height() - h * m_ScaleY)/2) + scrH);
    QGraphicsView::mouseMoveEvent(event);
    if(m_selectEditingItem && m_selectEditingItem->isSelected()){
        //m_selectEditingItem->update();
        //updateAll();
        for(int k = 0; k < m_Selectlist.count(); k++){
            m_Selectlist[k]->setPos(m_Selectlist[k]->pos().toPoint());
            ImageItem* item = (ImageItem*)m_Selectlist[k];
            item->update();
        }
        //m_selectEditingItem->setPos(m_selectEditingItem->pos().toPoint());
        emit changeSelItemPos(m_selectEditingItem->pos().toPoint(), m_selectEditingItem->getId(), m_selectEditingItem->rect().toRect());
    }

    if(m_bGroupBand)
    {
        //  영역선택시 반올림 우하 -> 좌상 으로 선택시 영역 떨림해결
        //QRectF r((int)((m_startPos.x() + hValue)/m_ScaleX), (int)((m_startPos.y() + vValue)/m_ScaleY), (int)((ex - m_startPos.x())/m_ScaleX), (int)((ey - m_startPos.y())/m_ScaleY));
        QRectF r((int)((m_startPos.x())/1), (int)((m_startPos.y())/1), (int)((p2.x() - m_startPos.x())/1), (int)((p2.y() - m_startPos.y())/1));

        QRectF tempRect = r;
        if(r.left() > r.right()){
            r.setLeft(tempRect.right());
            r.setRight(tempRect.left());
        }
        if(r.top() > r.bottom()){
            r.setTop(tempRect.bottom());
            r.setBottom(tempRect.top());
        }
        m_SelectRect = r.toRect().translated(GetModifedPos());

        if(!m_RectItem){
            m_RectItem = scene()->addRect(QRectF(r.x(), r.y(), r.width(), r.height()));
            int z = 100;
            m_RectItem->setBrush( QColor(50,50,50) );
            m_RectItem->setPen( QPen(QColor(50,50,50), 0) );
            m_RectItem->setZValue(z);
            m_RectItem->setOpacity(0.5f);
        }
        //r.translate(m_enermyPix->pos());
        m_RectItem->setRect(r);

        if(!m_TextItem){
            //m_TextItem = (JistSimpleTextItem*)scene()->addSimpleText(QString(QLatin1String("[x:%1, y:%2, w:%3, h:%4]")).arg(r.x()).arg(r.y()).arg(r.width()).arg(r.height()));
           m_TextItem = new JistSimpleTextItem;
            m_TextItem->setText(QString(QLatin1String("[x:%1, y:%2, w:%3, h:%4]")).arg(m_SelectRect.x()).arg(m_SelectRect.y()).arg(m_SelectRect.width()).arg(m_SelectRect.height()));
            m_TextItem->setScale(1/m_ScaleX);
        }
       else{
            m_TextItem->setText(QString(QLatin1String("[x:%1, y:%2, w:%3, h:%4]")).arg(m_SelectRect.x()).arg(m_SelectRect.y()).arg(m_SelectRect.width()).arg(m_SelectRect.height()));
            m_TextItem->setPos(QPointF(r.bottomRight()));
       }
    }
}

void FigureEditor::mouseDoubleClickEvent(QMouseEvent *event)
{
    QRect rect = this->rect();
    QSize tempSize = m_Img.size();
    // 창크기 변경시 클릭좌표 보정 취소 => 이미지 교체시 중앙정렬 미완성
    QPoint mp = QPoint(0,0);//QPoint((rect.width() - tempSize.width()*m_ScaleX)/2, (rect.height() - tempSize.height()*m_ScaleY)/2);
    QScrollBar *hb = horizontalScrollBar();
    int hValue = ((QAbstractSlider*)hb)->value();

    QScrollBar *vb = this->verticalScrollBar();
    int vValue = ((QAbstractSlider*)vb)->value();

    //===================== 리스트에 추가 =============================================
    switch(m_eViewMode){
        case DEFAULT_VIEW:
        {
            if(m_RectItem && m_IsAdditive && m_RectItem->rect().intersects(QRect(m_canvas.GetTouchPos().x(), m_canvas.GetTouchPos().y(), 1, 1)))
            {
                m_RectItem->setFocus();

                AddSprite(false);
//                JistCommonData data;
//                data.m_bVisible = true;
//                //data.m_Name = m_Name;
//                data.m_Rect = m_SelectRect;
//        //        if(m_bGroupBand)
//        //            data.m_Rect = QRect(m_SelectRect.x() + 1, m_SelectRect.y() + 1, m_SelectRect.width() - 2, m_SelectRect.height() - 2);
//                QImage  cutImage = m_Img.copy(data.m_Rect);
//                QImage  cutImage = g_EmptyImage;
//                data.m_img = cutImage;
//                data.m_iImgIndex = m_pDocument->m_ImageTableWidget->currentIndex().row();
//                data.m_iSpriteIndex = m_pModel->rowCount();
//                int pCnt = m_pModel->rowCount();
//                m_pModel->addData(data);
//                int aCnt = m_pModel->rowCount();
//                // 이미 추가된 스프라이트면 스킵
//                if(pCnt == aCnt)
//                    return;
//                // 스프라이트 삭제후 추가될 경우 셀리스트및 신뷰 아이템 갱신
//                for(int a = 0; a < m_pDocument->m_CellData.count(); a++){
//                    for(int s = 0; s < m_pDocument->m_CellData[a].count(); s++){
//                        for(int c = 0; c < m_pDocument->m_CellData[a][s].count(); c++){
//                            int imgId = (m_pDocument->m_CellData[a][s][c]).m_iImgIndex;
//                            int spriteId = (m_pDocument->m_CellData[a][s][c]).m_iSpriteIndex;
//                            if(imgId == m_pDocument->m_iCurrentSpriteDataIndex
//                                    && spriteId == m_pDocument->m_SpriteTableWidget->currentIndex().row())
//                            {
//                                // 셀리스트의 갱신
//                                (m_pDocument->m_CellData[a][s][c]).m_img = data.m_img;
//                                // 신뷰의 갱신
//                                (m_pDocument->m_CellData[a][s][c]).m_pIItem->recalculateResult();
//                            }
//                        }
//                    }
//                }
//                if(m_pDocument->m_CellTableWidget)
//                    m_pDocument->m_CellTableWidget->refineViewNoUndo(m_pDocument->m_CellTableWidget->currentIndex().row());
//                if(m_pDocument->m_pSceneFrameFigure)
//                    m_pDocument->m_pSceneFrameFigure->m_canvas.update();
//                m_pDocument->getCurrentSpriteData()->m_iImgIndex = data.m_iImgIndex;
//                m_pDocument->getCurrentSpriteData()->m_iSpriteIndex = data.m_iSpriteIndex;
//                m_pDocument->m_isAddedResource = true;
//                m_pDocument->currentIndexChanged();
//                // anchor point 추가
//                m_pDocument->getCurrentSpriteData()->m_Object.setProperty(tr("ancX"), QString::number(data.width()/2));
//                m_pDocument->getCurrentSpriteData()->m_Object.setProperty(tr("ancY"), QString::number(data.height()/2));
//                m_pDocument->getCurrentSpriteData()->m_AnchorPoint.setX(data.width()/2);
//                m_pDocument->getCurrentSpriteData()->m_AnchorPoint.setY(data.height()/2);
//                m_pDocument->setSpriteView(m_pDocument->m_SpriteTableWidget->currentIndex());
            }
        }break;
        case SPRITE_VIEW:
        {
            // 충돌영역 추가
            if(m_RectItem && m_IsAdditive && m_RectItem->rect().intersects(QRect(m_canvas.GetTouchPos().x(), m_canvas.GetTouchPos().y(), 1, 1)))
            {
                m_RectItem->setFocus();
                JistCommonData *data = m_pDocument->m_SpriteTableWidget->GetCurrentData();
                data->m_CollisionRect = m_RectItem->rect().translated(GetModifedPos()).toRect();
                JistDocumentHandler::instance()->SyncAllObject();
            }
        }break;
    }
    QList<QGraphicsItem *> list = m_canvas.selectedItems();
    if(list.count() && m_pDocument->m_CellTableWidget){
        //m_selectEditingItem = NULL;
        if(m_bMovable)
            m_pDocument->m_CellTableWidget->selectAll();;
    }
}

/**
 * Override to support zooming in and out using the mouse wheel.
 */
void FigureEditor::wheelEvent(QWheelEvent *event)
{
    if (event->modifiers() & Qt::ControlModifier
        && event->orientation() == Qt::Vertical)
    {
        // No automatic anchoring since we'll do it manually
        setTransformationAnchor(QGraphicsView::NoAnchor);

        //mZoomable->handleWheelDelta(event->delta());

        //adjustCenterFromMousePosition(mLastMousePos);

        // Restore the centering anchor
        setTransformationAnchor(QGraphicsView::AnchorViewCenter);
        setScale(1 + (event->delta()/1000.0), 1 + (event->delta()/1000.0));
        QPen pen(Qt::SolidLine);
        pen.setColor(QColor(255,0,0,255));
        if(m_ScaleX < 1.0){
            pen.setWidth(1/m_ScaleX);
            if(m_AnchorVLine)
                m_AnchorVLine->setPen(pen);
            if(m_AnchorHLine)
                m_AnchorHLine->setPen(pen);
        }
        return;
    }

    QGraphicsView::wheelEvent(event);

    // When scrolling the mouse does not move, but the view below it does.
    // This affects the mouse scene position, which needs to be updated.
   // mLastMouseScenePos = mapToScene(viewport()->mapFromGlobal(mLastMousePos));
}

void FigureEditor::exchangeSprite()
{
    QModelIndex tempCurrent = m_pDocument->m_SpriteTableWidget->currentIndex();
    int index = tempCurrent.row();
    JistCommonModel* m = (JistCommonModel*)(m_pDocument->m_SpriteTableWidget->model());
    JistCommonData data = m->m_pList->value(index);
    {
        data.m_bVisible = true;
        //data.m_Name = m_Name;
        data.m_Rect = m_SelectRect;
        QImage  cutImage = m_Img.copy(data.m_Rect);
        data.m_img = cutImage;
        data.m_UIOpt = 0;
        m->setData(tempCurrent,data.m_Rect, Qt::UserRole);
        m->setData(tempCurrent,data.m_img, Qt::UserRole+2);
        m->setData(tempCurrent,data.m_UIOpt, Qt::UserRole+3);
        m_pDocument->setSpriteView(tempCurrent);
        // 스프라이트 삭제후 추가될 경우 셀리스트및 신뷰 아이템 갱신
        for(int a = 0; a < m_pDocument->m_CellData.count(); a++){
            for(int s = 0; s < m_pDocument->m_CellData[a].count(); s++){
                for(int c = 0; c < m_pDocument->m_CellData[a][s].count(); c++){
                    int imgId = (m_pDocument->m_CellData[a][s][c]).m_iImgIndex;
                    int spriteId = (m_pDocument->m_CellData[a][s][c]).m_iSpriteIndex;
                    if(imgId == m_pDocument->m_iCurrentSpriteDataIndex
                            && spriteId == m_pDocument->m_SpriteTableWidget->currentIndex().row())
                    {
                        // 셀리스트의 갱신
                        (m_pDocument->m_CellData[a][s][c]).m_img = data.m_img;
                        // 신뷰의 갱신
                        (m_pDocument->m_CellData[a][s][c]).m_pIItem->recalculateResult();
                    }
                }
            }
        }
    }

 }

void FigureEditor::clearColision()
{
    JistCommonData *data = m_pDocument->m_SpriteTableWidget->GetCurrentData();
    data->m_CollisionRect = QRect();
    update();
    scene()->removeItem(m_RectItem);
    scene()->removeItem(m_TextItem);
    m_RectItem = NULL;
    m_TextItem = NULL;
    JistDocumentHandler::instance()->SyncAllObject();
}

void FigureEditor::mouseReleaseEvent(QMouseEvent *event)
{
    if(m_bMovable || m_bDragMovable)
        QGraphicsView::mouseReleaseEvent(event);
    else
        return;

    if (event->button() != Qt::LeftButton)
        return;

    // 리스트뷰와 셀렉팅연동
    m_Selectlist = m_canvas.selectedItems();
    if(!m_Selectlist.isEmpty()){
        qSort(m_Selectlist.begin(), m_Selectlist.end());
    }
    bool isSync = false;

//    for(int k = 0; k < m_Selectlist.count(); k++){
//        ImageItem* item = (ImageItem*)m_Selectlist[k];
//        int id = item->getId();
//        //m_pDocument->m_CellTableWidget->selectRow(id);
//        // 선택된 셀이 선택된 신의 셀인지 검사
//        int listCnt = m_pDocument->m_CellData[m_pDocument->m_iCurrentSceneDataIndex][m_pDocument->m_iCurrentCellDataIndex].count();
//        if(listCnt > id && m_pDocument->m_CellData[m_pDocument->m_iCurrentSceneDataIndex][m_pDocument->m_iCurrentCellDataIndex][id].m_pIItem == item){
//            m_pDocument->m_CellTableWidget->setSelection(QRect(0,id*JistCommonDelegate::m_PixelSize + 20, 1, 1),QItemSelectionModel::Select);
//            isSync = true;
//        }
//    }

    //m_pDocument->m_CellTableWidget->setSelectionMode(QAbstractItemView::SingleSelection);
//    for(int k = 0; k < tableList.count() && m_Selectlist.count(); k++){
//        ImageItem* item = (ImageItem*)m_Selectlist[0];
//        if(tableList[k].m_pIItem == item){
//            m_pDocument->m_CellTableWidget->selectRow(k);
//            isSync = true;
//        }
//    }
//    if(!isSync)
//        m_pDocument->m_CellTableWidget->clearSelection();
    //m_pDocument->m_CellTableWidget->setSelectionMode(QAbstractItemView::SingleSelection);
    updateAll();
    // 리스트 셀렉팅-> 뷰 셀렉팅으로 모든 셀렉트 해제 -> 리스트에서 최근에 선택했던 리스트 클릭 => 선택 안됨 제거
//    if(m_Selectlist.count() == 1 && isSync){
//        ImageItem* item = (ImageItem*)m_Selectlist.first();
//        m_pDocument->m_CellTableWidget->selectRow(item->getId());
//    }
    if(m_Selectlist.count() == 1){
        QList< JistCommonData > tableList = m_pDocument->m_CellData[m_pDocument->m_iCurrentSceneDataIndex][m_pDocument->m_iCurrentCellDataIndex];
        for(int k = 0; k < tableList.count(); k++){
            ImageItem* item = (ImageItem*)m_Selectlist[0];
            if(tableList[k].m_pIItem == item){
                m_pDocument->m_CellTableWidget->selectRow(k);
            }
        }
    }
    //m_pDocument->m_CellTableWidget->setSelectionMode(QAbstractItemView::MultiSelection);
//    switch (mMode) {
//    case NoMode:
//        if (mClickedObjectItem) {
//            QSet<MapObjectItem*> selection = mapScene()->selectedObjectItems();
//            const Qt::KeyboardModifiers modifiers = event->modifiers();
//            if (modifiers & (Qt::ShiftModifier | Qt::ControlModifier)) {
//                if (selection.contains(mClickedObjectItem))
//                    selection.remove(mClickedObjectItem);
//                else
//                    selection.insert(mClickedObjectItem);
//            } else {
//                selection.clear();
//                selection.insert(mClickedObjectItem);
//            }
//            mapScene()->setSelectedObjectItems(selection);
//        } else {
//            mapScene()->setSelectedObjectItems(QSet<MapObjectItem*>());
//        }
//        break;
//    case Selecting:
//        updateSelection(event->scenePos(), event->modifiers());
//        mapScene()->removeItem(mSelectionRectangle);
//        mMode = NoMode;
//        break;
//    case Moving:
        finishMoving(event->pos());
//        break;
//    }
        // 리스트뷰와 셀렉팅연동
//    if(m_selectEditingItem){
//        m_selectedStartPos = m_selectEditingItem->pos();
//        for(int k = 0; k < m_pModel->rowCount(); k++)
//        {
//            if((JistCommonModel*)m_pModel->m_pList->at(k).m_pIItem->isSelected())
//                m_pModel->m_pView->selectRow(k);
//        }
//    }

//    mMousePressed = false;
//    mClickedObjectItem = 0;
}

// 셀아이템의 이동관리
void FigureEditor::finishMoving(const QPointF &pos)
{

    if (m_startPos == pos || !m_selectEditingItem){ // Move is a no-op
        return;
    }

    QUndoStack *undoStack = m_pDocument->undoStack();
    undoStack->beginMacro(tr("Move Cell"));

    QPointF p = m_selectEditingItem->pos();
    QPointF dPos(p.x() - m_selectedStartPos.x(), p.y() -  m_selectedStartPos.y());
    undoStack->push(new MoveCell(m_pDocument, m_Selectlist, dPos.toPoint()));

    undoStack->endMacro();
    m_selectEditingItem = NULL;
}

void FigureEditor::updateAll()
{
    QList<QGraphicsItem *> list =  m_canvas.items();
    int cnt = list.count();


    for(int k = list.count() -1; k > 0 ; k--)
    {
        ImageItem* item = dynamic_cast<ImageItem*>(list.at(k));//(ImageItem*)list.at(k);
        // 그리드 제외
        if(item && !item->m_Image.isNull())
		  item->update();
    }
}

bool FigureEditor::isDrawable(const int x, const int y) const
{
    QRgb c = m_Img.pixel(x, y);
    // Silently quit if parameters are unsatisfactory
    if (!qAlpha(c))
        return false;
    return true;
}

void FigureEditor::setDocument(JistDocument *doc)
{
    m_pDocument = doc;
}

void FigureEditor::setModel(JistCommonModel *model)
{
    m_pModel = model;
}

void FigureEditor::setAdditive(bool isAdditive)
{
    m_IsAdditive = isAdditive;
}

QGraphicsPixmapItem* FigureEditor::setImage( QImage img)
{
    QFile file(getName());
    file.open(QIODevice::ReadOnly);
    QByteArray arrBmp = file.readAll();
    file.close();
    m_Img = img.convertToFormat(QImage::Format_ARGB32);
    //creatFakeBMP();
    QPixmap qpi = QPixmap::fromImage(m_Img);
    m_canvas.clear();
    m_enermyPix = m_canvas.addPixmap(qpi);
    return m_enermyPix;
}

// 스프라이트 뷰에 충돌영역 동기화
void FigureEditor::SetRectItem()
{
    if(!m_RectItem && m_pDocument->getCurrentSpriteData()){
        QRect oriRect = m_pDocument->getCurrentSpriteData()->m_CollisionRect;
        QRect rect = m_pDocument->getCurrentSpriteData()->m_CollisionRect.translated(m_canvas.width()/2, m_canvas.height()/2);
        m_RectItem = scene()->addRect(QRectF(rect.x(), rect.y(), rect.width(), rect.height()));
        int z = 100;
        m_RectItem->setBrush( QColor(50,0,0) );
        m_RectItem->setPen( QPen(QColor(255,50,50), 0) );
        m_RectItem->setZValue(z);
        m_RectItem->setOpacity(0.2f);
        if(rect.width()){
            if(!m_TextItem){
                //m_TextItem = (JistSimpleTextItem*)scene()->addSimpleText(QString(QLatin1String("[x:%1, y:%2, w:%3, h:%4]")).arg(r.x()).arg(r.y()).arg(r.width()).arg(r.height()));
               m_TextItem = new JistSimpleTextItem;
                m_TextItem->setText(QString(QLatin1String("[x:%1, y:%2, w:%3, h:%4]")).arg(oriRect.x()).arg(oriRect.y()).arg(oriRect.width()).arg(oriRect.height()));
                m_TextItem->setScale(1/m_ScaleX);
                m_TextItem->setPos(QPointF(rect.bottomRight()));
           }
           else{
                m_TextItem->setText(QString(QLatin1String("[x:%1, y:%2, w:%3, h:%4]")).arg(oriRect.x()).arg(oriRect.y()).arg(oriRect.width()).arg(oriRect.height()));
                m_TextItem->setPos(QPointF(rect.bottomRight()));
           }
           scene()->addItem(m_TextItem);
        }
    }
}

int FigureEditor::NextPot(int n)
{
    n--;
    n|=n>>1;n|=n>>2;
    n|=n>>4;n|=n>>8;
    n|=n>>16;
    n++;
    return n;
}

void FigureEditor::creatFakeBMP()
{
    if(m_Name.contains(tr("@") ))
		return;
    int w = NextPot(m_Img.width());
    int h = NextPot(m_Img.height());
    QImage img(w, h, QImage::Format_ARGB32);
    img.fill(0);

    QPainter pPan(&img);
    pPan.drawImage(m_Img.rect(), m_Img, m_Img.rect());
    for(int y = 0; y < m_Img.height(); y++){
        for(int x = 0; x < m_Img.width(); x++){
            //char color = arrBmp[57+ x*4 +  y*m_Img.width()*4];
            QRgb color = m_Img.pixel(x,y);
            if(qAlpha(color) == 0)
                //m_Img.setPixel(x,(m_Img.height()- y - 1), 0x00000000);
                m_Img.setPixel(x, y, 0);
        }
    }

    QString newStr = m_Name;
//    newStr.replace(".png","new.png");
//    img.save(newStr, "png");

    newStr = m_Name.replace(tr(".png"), tr(".bmp"));
    newStr = m_Name.replace(tr(".PNG"), tr(".bmp"));
    img.save(newStr, "png");
}

void FigureEditor::addImage( QImage img)
{
    QPixmap  qpi = QPixmap::fromImage(img);

    scene()->addPixmap(qpi)->setFlag(QGraphicsItem::ItemIsMovable);
    scene()->addPixmap(qpi)->setFlag(QGraphicsItem::ItemIsSelectable);
}

void FigureEditor::setScale(qreal sx, qreal sy)
{
    if(sx > 0)
        m_ScaleX *= sx;
    if(sy > 0)
        m_ScaleY *= sy;
    this->scale(sx, sy);
    if(m_TextItem){
        m_TextItem->setScale(1/m_ScaleX);
    }
}

//==================================================================
//                      애니메이션 관련
//==================================================================

void FigureEditor::setPlayState(bool isPlaying)
{
    m_bAniPlaying = isPlaying;
}

void FigureEditor::resetAni()
{
    m_iFrameIndex = 0;
	// 버그수정 신이 많은 세이브파일로드후 적은 파일 로드 다시 많은 파일로드시 
    int c = m_CellData[0].count();
    if(m_CellData.empty() || !m_CellData[0].count() || !m_CellData[0][0].count())
        return;
    m_canvas.clear();
    QGraphicsPixmapItem* pi = setImage(m_EnermyImage);
    pi->setPos(X1,Y2);
    pi->setZValue(-100);
//    for(int i = 0; m_iAnimationIndex < m_CellData.count() && i < (m_CellData[m_iAnimationIndex]).count(); i++)
//    {
//        for(int k = 0; k < m_CellData[m_iAnimationIndex][i].count(); k++)
//        {
//            // 현재 셀 비표시하기
//            //(m_CellData[m_iAnimationIndex][i][k]).m_pIItem->setVisible(false);
//            m_canvas.removeItem(m_CellData[m_iAnimationIndex][i][k].m_pIItem);
//        }
//    }
}

void FigureEditor::animate()
{
    // 새로 만들기 오류수정
    if(m_CellData.empty() || m_CellData[0][0].empty())
        return;
    m_canvas.clear();
    QGraphicsPixmapItem* pi = setImage(m_EnermyImage);
    pi->setPos(m_enermyPixPos);
    pi->setZValue(-100);
//    for(int k = 0; k < m_CellData[m_iAnimationIndex][m_iFrameIndex].count(); k++)
//    {
//        // 현재 셀 비표시하기
////        m_CellData[m_iAnimationIndex][m_iFrameIndex][k].m_pIItem->setVisible(false);
//        m_canvas.removeItem(m_CellData[m_iAnimationIndex][m_iFrameIndex][k].m_pIItem);

//    }
    int aniCnt = m_pDocument->m_AnimationData.count();
    for(int j = 0; j <  aniCnt; j++){
        for(int k = 0; k < m_CellData[j][0].count() && m_pDocument->m_AnimationData[j].m_bVisible && m_iAnimationIndex != j; k++)
        {
            // 현재 셀 표시하기
            //m_CellData[m_iAnimationIndex][m_iFrameIndex][k].m_pIItem->setVisible(true);
            //m_canvas.addItem(m_CellData[m_iAnimationIndex][m_iFrameIndex][k].m_pIItem);
            // 아이템이 추가되지만
            //If the item is already in a different scene,
            //it will first be removed from its old scene, and then added to this scene as a top-level.
            JistCommonData data;
            data.copyData(m_CellData[j][0][k]);
            addItem(data.m_pIItem);
        }
    }

    for(int k = 0; k < m_CellData[m_iAnimationIndex][m_iFrameIndex].count(); k++)
    {
        // 현재 셀 표시하기
        //m_CellData[m_iAnimationIndex][m_iFrameIndex][k].m_pIItem->setVisible(true);
        //m_canvas.addItem(m_CellData[m_iAnimationIndex][m_iFrameIndex][k].m_pIItem);
        // 아이템이 추가되지만
        //If the item is already in a different scene,
        //it will first be removed from its old scene, and then added to this scene as a top-level.
        JistCommonData data;
        data.copyData(m_CellData[m_iAnimationIndex][m_iFrameIndex][k]);
        addItem(data.m_pIItem);
    }

    if(m_bReverse) // 역재생
    {
        m_iFrameIndex--;
        if(0 > m_iFrameIndex){
            if(m_bLoopAni)
                // 새로만들때 생긴 빈 애니메이션 리스트데이터 스킵
                if(!m_CellData[m_iAnimationIndex][m_CellData[m_iAnimationIndex].count() - 1].isEmpty())
                    m_iFrameIndex = m_CellData[m_iAnimationIndex].count() - 1;
                else
                    m_iFrameIndex = m_CellData[m_iAnimationIndex].count() - 2;
            else
                m_iFrameIndex = 0;
        }
    }
    else // 재생
    {
        m_iFrameIndex++;
        // 새로만들때 생긴 빈 애니메이션 리스트데이터 스킵
        if(m_CellData[m_iAnimationIndex].count() <= m_iFrameIndex || m_CellData[m_iAnimationIndex][m_iFrameIndex].isEmpty())
        {
            if(m_bLoopAni)
                m_iFrameIndex = 0;
            else
                if(!m_CellData[m_iAnimationIndex][m_CellData[m_iAnimationIndex].count() - 1].isEmpty())
                    m_iFrameIndex = m_CellData[m_iAnimationIndex].count() - 1;
                else
                    m_iFrameIndex = m_CellData[m_iAnimationIndex].count() - 2;
        }

    }


}
//========== 삭제예정 ================
void FigureEditor::setName(QString s)
{
    m_Name = s;
}

QString FigureEditor::getName()
{
    return m_Name;
}
//=====================================
void FigureEditor::setMovableTouch(bool movable)
{
    // 전체화면 드래그시 이동기능추가로 주석처리됨
    m_bMovable = movable;
    setCacheMode(QGraphicsView::CacheBackground);
    setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate);

}


void FigureEditor::setRect(QRect r)
{
    //this->setGeometry(r);
    if(m_bShowEnermy || m_bShowGrid)
    {
        if(m_EnermyImage.isNull())
        {
            m_EnermyImage = QImage(tr(":/images/small.png"));
            m_enermyPix = setImage(m_EnermyImage);
            m_enermyPix->setPos(X1,Y2 + 96 - m_EnermyImage.height());
            m_enermyPix->setZValue(-100);
            m_enermyPixPos = m_enermyPix->pos();
            X2 = X1 + m_EnermyImage.width();
        }

        // 그리드 라인 그리기
        QPen pen(Qt::DotLine);
        pen.setWidth(1);
        pen.setColor(QColor(255,255,255,128));
        //QRectF r(this->rect());
        //QRectF r(QRect(0,0, 960, 640));
        //QGraphicsRectItem *item = m_canvas.addRect(r, pen);

        QGraphicsLineItem *line = m_canvas.addLine(QLine(X1, 0, X1, r.height()), pen);
        line->setZValue(-100);

        line = m_canvas.addLine(QLine(X3, 0, X3, r.height()), pen);
        line->setZValue(-100);
        line = m_canvas.addLine(QLine(0, Y1, r.width(), Y1), pen);
        line->setZValue(-100);
        line = m_canvas.addLine(QLine(0, Y2, r.width(), Y2), pen);
        line->setZValue(-100);
        line = m_canvas.addLine(QLine(0, Y3, r.width(), Y3), pen);
        // 언두리두 적용시 그리드 아이템이 선택 되는거 방지
        line->setZValue(-100);
        pen.setStyle(Qt::SolidLine);
        m_LineX2 = m_canvas.addLine(QLine(X2, 0, X2, r.height()), pen);
        m_LineX2->setZValue(-100);

        pen.setColor(QColor(255,255,0,255));
        line = m_canvas.addLine(QLine(0, 256, r.width(), 256), pen);
        line->setZValue(-100);
        line->setOpacity(0.5);
        line = m_canvas.addLine(QLine(0, 416, r.width(), 416), pen);
        line->setZValue(-100);
        line->setOpacity(0.5);
        // 적과의 간격 한계선
        pen.setColor(QColor(255,0,0,255));
        m_LineRange = m_canvas.addLine(QLine(X2 + OPPOSIT_SPACE, 0, X2 + OPPOSIT_SPACE, r.height()), pen);
        m_LineRange->setZValue(-100);
        m_LineRange->setOpacity(0.5);

        changeEnermy(0);
    }
    if(m_bShowGrid)
    {

    }

}

void FigureEditor::changeEnermy(int monType)
{
    int targetX[2] = { 56, 136};
    // 그리드 라인 그리기
    QPen pen(Qt::SolidLine);
    pen.setWidth(1);
    pen.setColor(QColor(255,255,255,255));
    //QRectF r(this->rect());
    //QRectF r(QRect(0,0, 960, 640));
    //QGraphicsRectItem *item = m_canvas.addRect(r, pen);
    QString monPath[2] = {tr(":/images/small.png"), tr(":/images/bigMon.png")};
    int preImgH = m_EnermyImage.height();
    m_EnermyImage = QImage(monPath[monType]);
    QPointF p = m_enermyPix->pos();
    int curH = m_EnermyImage.height();
    QPixmap qpi = QPixmap::fromImage(m_EnermyImage);
    m_enermyPix->setPixmap(qpi);
    m_enermyPix->setPos(m_enermyPix->pos().x(), m_enermyPix->pos().y() + (preImgH - m_EnermyImage.height()));
    m_enermyPix->update();
    m_enermyPixPos = m_enermyPix->pos();
    X2 = X1 + targetX[monType];
    if(m_bShowGrid)
    {
        m_LineX2->setLine(X2, 0, X2, 640);
        m_LineRange->setLine(X2 + OPPOSIT_SPACE, 0, X2 + OPPOSIT_SPACE, 640);
    }
}

void FigureEditor::addItem(ImageItem* item)
{
    m_canvas.addItem(item);
    if(m_bMovable)
    {
        item->setFlag(QGraphicsItem::ItemIsSelectable);
        item->setFlag(QGraphicsItem::ItemIsMovable);
    }
    item->update();
    QGraphicsScene  *gs = item->scene();
    //connect(this, SIGNAL(changed ( const QList<QRectF> & )), item, SLOT(update()));
}

// 영역 선택 Tiled 에서 가져옴
QRect FigureEditor::computeFillRegion(const QPoint &fillOrigin) const
{
    // Create that region that will hold the fill
    QRegion fillRegion;
    QRgb c = m_Img.pixel(fillOrigin);
    // Silently quit if parameters are unsatisfactory
    if (!qAlpha(c))
        //return fillRegion;
        return QRect(0, 0, 0, 0);
    // Cache cell that we will match other cells against
    const QRgb matchCell = m_Img.pixel(fillOrigin.x(), fillOrigin.y());

    // Grab map dimensions for later use.
    const int mapWidth = m_Img.width();
    const int mapHeight = m_Img.height();
    const int mapSize = mapWidth * mapHeight;
    int maxRight = 0;
    int maxLeft = mapWidth;
    int maxTop = mapHeight;
    int maxBottom = 0;
    // Create a queue to hold cells that need filling
    QList<QPoint> fillPositions;
    fillPositions.append(fillOrigin);

    // Create an array that will store which cells have been processed
    // This is faster than checking if a given cell is in the region/list
    QVector<quint8> processedCellsVec(mapSize);
    quint8 *processedCells = processedCellsVec.data();

    // Loop through queued positions and fill them, while at the same time
    // checking adjacent positions to see if they should be added
    while (!fillPositions.empty()) {
        const QPoint currentPoint = fillPositions.takeFirst();
        const int startOfLine = currentPoint.y() * mapWidth;

        // Seek as far left as we can
        int left = currentPoint.x();
        if(left < maxLeft)
            maxLeft = left;
        while (/*m_Img.pixel(left - 1, currentPoint.y()) == matchCell &&*/
               isDrawable(left - 1, currentPoint.y()))
        {
            --left;
            if(left < maxLeft)
                maxLeft = left;
        }

        // Seek as far right as we can
        int right = currentPoint.x();
        if(right > maxRight)
            maxRight = right;
        while (/*m_Img.pixel(right + 1, currentPoint.y()) == matchCell &&*/
               isDrawable(right + 1, currentPoint.y()))
        {
            ++right;
            if(right > maxRight)
                maxRight = right;
        }
        // Add cells between left and right to the region
        fillRegion += QRegion(left, currentPoint.y(), right - left + 1, 1);

        // Add cell strip to processed cells
        memset(&processedCells[startOfLine + left],
               1,
               right - left);

        // These variables cache whether the last cell was added to the queue
        // or not as an optimization, since adjacent cells on the x axis
        // do not need to be added to the queue.
        bool lastAboveCell = false;
        bool lastBelowCell = false;

        // Loop between left and right and check if cells above or
        // below need to be added to the queue
        for (int x = left; x <= right; ++x) {
            const QPoint fillPoint(x, currentPoint.y());

            // Check cell above
            if (fillPoint.y() > 0) {
                QPoint aboveCell(fillPoint.x(), fillPoint.y() - 1);
                if (!processedCells[aboveCell.y()*mapWidth + aboveCell.x()] &&
                    /*m_Img.pixel(aboveCell.x(), aboveCell.y()) == matchCell &&*/
                    isDrawable(aboveCell.x(), aboveCell.y()))
                {
                    // Do not add the above cell to the queue if its
                    // x-adjacent cell was added.
                    if (!lastAboveCell)
                        fillPositions.append(aboveCell);
                    if(aboveCell.y() < maxTop)
                        maxTop = aboveCell.y();
                    lastAboveCell = true;
                } else lastAboveCell = false;

                processedCells[aboveCell.y() * mapWidth + aboveCell.x()] = 1;
            }

            // Check cell below
            if (fillPoint.y() + 1 < mapHeight) {
                QPoint belowCell(fillPoint.x(), fillPoint.y() + 1);
                if (!processedCells[belowCell.y()*mapWidth + belowCell.x()] &&
                    /*m_Img.pixel(belowCell.x(), belowCell.y()) == matchCell &&*/
                    isDrawable(belowCell.x(), belowCell.y()))
                {
                    // Do not add the below cell to the queue if its
                    // x-adjacent cell was added.
                    if (!lastBelowCell)
                        fillPositions.append(belowCell);
                    if(belowCell.y() > maxBottom)
                        maxBottom = belowCell.y();
                    lastBelowCell = true;
                } else lastBelowCell = false;

                processedCells[belowCell.y() * mapWidth + belowCell.x()] = 1;
            }
        }
    }

    QRect rect(maxLeft, maxTop,(maxRight - maxLeft + 1),(maxBottom - maxTop + 1));
    return rect;
}


void FigureEditor::contextMenuEvent(QContextMenuEvent *event)
{

    QPoint mp = QPoint(0,0);//QPoint((rect.width() - tempSize.width()*m_ScaleX)/2, (rect.height() - tempSize.height()*m_ScaleY)/2);
    QScrollBar *hb = horizontalScrollBar();
    int hValue = ((QAbstractSlider*)hb)->value();

    QScrollBar *vb = this->verticalScrollBar();
    int vValue = ((QAbstractSlider*)vb)->value();


    JistDocumentHandler *handler = JistDocumentHandler::instance();

    QMenu menu;

    if(m_RectItem && m_IsAdditive && m_RectItem->rect().intersects(QRect(m_canvas.GetTouchPos().x() / 1, m_canvas.GetTouchPos().y() / 1, 1, 1)))
    {
     //   case SPRITELIST_CHANGE:
        {
//            if(currentIndex().row() != -1 && m_pDocument->m_SceneTableWidget->currentIndex().row() != -1)
//                handler->actionAddCell()->setEnabled(true);
//            else
//                handler->actionAddCell()->setEnabled(false);

//            int index = currentIndex().row();
//            JistCommonModel* m = (JistCommonModel*)(this->model());
//            JistCommonData data = m->m_pList->value(index);
            char *menuStr = "다듬기";
            char *menuUndoStr = "되돌리기";

            QTextCodec *codec = QTextCodec::codecForName("UTF-8");
            QString localeStr = codec->toUnicode(menuStr);
            QString localeUndoStr = codec->toUnicode(menuUndoStr);
            switch(m_eViewMode){
                case DEFAULT_VIEW:
                {
                    menu.addAction(handler->mActionExchangeSprite);
                }break;
                case SPRITE_VIEW:
                {
                    menu.addAction(handler->mActionClearColision);
                }break;
            }

            menu.exec(event->globalPos());
            //break;
        }
    }

}

QPoint FigureEditor::GetModifedPos()
{
    switch(m_eViewMode){
        case DEFAULT_VIEW:
        {
             return QPoint(0, 0);
        }break;
        case SPRITE_VIEW:
        {
             return QPoint(-m_canvas.width()/2, -m_canvas.height()/2);
        }break;
    }

}

QPoint FigureEditor::GetAnchorPos()
{
    switch(m_eViewMode){
        case DEFAULT_VIEW:
        {
             return QPoint(0, 0);
        }break;
        case SPRITE_VIEW:
        {
             return QPoint(m_enermyPix->pos().x() - m_canvas.width()/2, m_enermyPix->pos().y() - m_canvas.height()/2);
        }break;
    }
}


/*
void FigureEditor::mouseReleaseEvent(QMouseEvent *event)
{
    QScrollBar *hb = horizontalScrollBar();
    int hvalue = ((QAbstractSlider*)hb)->value();

    QScrollBar *vb = this->verticalScrollBar();
    QPoint p = event->pos();

}


void FigureEditor::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);

//    painter.begin(this);
//    painter.save();
    QBrush b(Qt::darkBlue);
    painter.setBrush(QColor("#ffcccc"));
    painter.fillRect(event->rect(), Qt::darkGray);
    //if (highlightedRect.isValid()) {
    //    painter.setBrush(QColor("#ffcccc"));
    //    painter.setPen(Qt::NoPen);
        //painter.drawRect(highlightedRect.adjusted(0, 0, -1, -1));
    //}

    //for (int i = 0; i < pieceRects.size(); ++i) {
        //painter.drawPixmap(pieceRects[i], piecePixmaps[i]);
    //}
    //painter.drawImage(0,0,m_Img);
    //QGraphicsView::paintEvent(event);
    //painter.restore();
    //painter.end();
}
*/
/*void FigureEditor::render( QPainter * painter, const QRectF & target, const QRect & source, Qt::AspectRatioMode aspectRatioMode )
{
    m_buffImg = new QImage(size(),QImage::Format_ARGB32_Premultiplied);
    //printer.setPageSize(QPrinter::A4);
    QPainter painter2(m_buffImg);

    // print, fitting the viewport contents into a full page
    render(&painter2);
}

void FigureEditor::paintEvent ( QPaintEvent * event )
{
    QGraphicsView::paintEvent (event);
    QPainter painter(this);
     painter.setBrush(QColor("#ffcccc"));
     QPen pen(Qt::black, Qt::SolidLine);
     painter.setPen(pen);
    //painter.begin(this);
    //painter.setRenderHint(QPainter::Antialiasing);
    painter.fillRect(event->rect(), QBrush(QColor(64, 32, 64)));
    painter.drawLine(0,0,100,100);
//painter.restore();
//    painter.end();

}
*/
void FigureEditor::drawBackground( QPainter * painter, const QRectF & rect )
{
    QGraphicsView::drawBackground(painter, rect );
//    int w = FigureEditor::window()->size().width();
//    painter->drawLine(QPoint(0, rect.height()/2), QPoint(rect.width(), rect.height()/2));
//    painter->drawLine(QPoint(rect.width()/2, 0), QPoint(rect.width()/2, rect.height()));
//    QImage *image;
//    image->load(":/images/bg.bmp");
//    painter->drawImage(rect,*image,rect);
}

void FigureEditor::AddSprite(bool isEmptySprite)
{
    JistCommonData data;
    data.m_bVisible = true;
    //data.m_Name = m_Name;
    data.m_Rect = m_SelectRect;
    //        if(m_bGroupBand)
    //            data.m_Rect = QRect(m_SelectRect.x() + 1, m_SelectRect.y() + 1, m_SelectRect.width() - 2, m_SelectRect.height() - 2);

    QImage  cutImage = m_Img.copy(data.m_Rect);
    if(isEmptySprite)
        cutImage = g_EmptyImage;
    data.m_img = cutImage;
    data.m_iImgIndex = m_pDocument->m_ImageTableWidget->currentIndex().row();
    data.m_iSpriteIndex = m_pModel->rowCount();
    int pCnt = m_pModel->rowCount();
    m_pModel->addData(data);
    int aCnt = m_pModel->rowCount();
    // 이미 추가된 스프라이트면 스킵
    if(pCnt == aCnt)
        return;
    // 스프라이트 삭제후 추가될 경우 셀리스트및 신뷰 아이템 갱신
    for(int a = 0; a < m_pDocument->m_CellData.count(); a++){
        for(int s = 0; s < m_pDocument->m_CellData[a].count(); s++){
            for(int c = 0; c < m_pDocument->m_CellData[a][s].count(); c++){
                int imgId = (m_pDocument->m_CellData[a][s][c]).m_iImgIndex;
                int spriteId = (m_pDocument->m_CellData[a][s][c]).m_iSpriteIndex;
                if(imgId == m_pDocument->m_iCurrentSpriteDataIndex
                        && spriteId == m_pDocument->m_SpriteTableWidget->currentIndex().row())
                {
                    // 셀리스트의 갱신
                    (m_pDocument->m_CellData[a][s][c]).m_img = data.m_img;
                    // 신뷰의 갱신
                    (m_pDocument->m_CellData[a][s][c]).m_pIItem->recalculateResult();
                }
            }
        }
    }
    if(m_pDocument->m_CellTableWidget)
        m_pDocument->m_CellTableWidget->refineViewNoUndo(m_pDocument->m_CellTableWidget->currentIndex().row());
    if(m_pDocument->m_pSceneFrameFigure)
        m_pDocument->m_pSceneFrameFigure->m_canvas.update();
    m_pDocument->getCurrentSpriteData()->m_iImgIndex = data.m_iImgIndex;
    m_pDocument->getCurrentSpriteData()->m_iSpriteIndex = data.m_iSpriteIndex;
    m_pDocument->m_isAddedResource = true;
    m_pDocument->currentIndexChanged();
    // anchor point 추가
    m_pDocument->getCurrentSpriteData()->m_Object.setProperty(tr("ancX"), QString::number(data.width()/2));
    m_pDocument->getCurrentSpriteData()->m_Object.setProperty(tr("ancY"), QString::number(data.height()/2));
    m_pDocument->getCurrentSpriteData()->m_AnchorPoint.setX(data.width()/2);
    m_pDocument->getCurrentSpriteData()->m_AnchorPoint.setY(data.height()/2);
    m_pDocument->setSpriteView(m_pDocument->m_SpriteTableWidget->currentIndex());

}


void jistCanvas::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
     m_TouchPos = event->scenePos().toPoint();
}


void jistCanvas::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
    m_TouchPos = event->scenePos().toPoint();
}

